package com.hck.infrastructure.persistent.repository;

import com.hck.api.model.AuthenticateRequestDTO;
import com.hck.domain.user.model.entity.UserEntity;
import com.hck.domain.user.repository.UserRepository;
import com.hck.infrastructure.persistent.dao.IUserDao;
import com.hck.infrastructure.persistent.po.User;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;

/**
 * 用户仓储实现类
 */
@Repository
public class UserRepositoryImpl implements UserRepository {
    
    @Resource
    private IUserDao userDao;
    
    @Override
    public UserEntity findByUsername(String username) {
        User user = userDao.selectByUsername(username);
        return convertToDomain(user);
    }
    
    @Override
    public UserEntity findById(Long userId) {
        User user = userDao.selectById(userId);
        return convertToDomain(user);
    }
    
    @Override
    public void save(UserEntity userEntity) {
        User user = convertToPO(userEntity);
        userDao.insert(user);
    }
    
    @Override
    public void update(UserEntity userEntity) {
        System.out.println("更新用户到数据库: userId=" + userEntity.getId() + ", avatar=" + userEntity.getAvatar());
        User user = convertToPO(userEntity);
        int result = userDao.update(user);
        System.out.println("数据库更新结果: " + result + " 行受影响");
    }
    
    @Override
    public boolean existsByUsername(String username) {
        return userDao.existsByUsername(username);
    }
    
    @Override
    public boolean existsByPhone(String phone) {
        return userDao.existsByPhone(phone);
    }
    
    @Override
    public boolean existsByEmail(String email) {
        return userDao.existsByEmail(email);
    }
    
    @Override
    public boolean existsByIdCard(String idCard) {
        return userDao.existsByIdCard(idCard);
    }

    @Override
    public boolean authentic(AuthenticateRequestDTO authenticateRequestDTO) {
        String password = authenticateRequestDTO.getPassword();
        Long userId = authenticateRequestDTO.getUserId();
        return userDao.authentic(userId,password);
    }


    /**
     * 将PO转换为领域对象
     */
    private UserEntity convertToDomain(User user) {
        if (user == null) {
            return null;
        }
        UserEntity userEntity = new UserEntity();
        BeanUtils.copyProperties(user, userEntity);
        return userEntity;
    }
    
    /**
     * 将领域对象转换为PO
     */
    private User convertToPO(UserEntity userEntity) {
        if (userEntity == null) {
            return null;
        }
        User user = new User();
        BeanUtils.copyProperties(userEntity, user);
        return user;
    }
} 